<template>
  <div class="role-wrap">
    <el-tabs v-model="currenltTab" @tab-click="handleClick">
      <div class="btn-group">
        <el-button type="primary" icon="el-icon-circle-plus" @click="addSort">添加顶级菜单</el-button>
        <el-button icon="el-icon-refresh" @click="refresh()">刷新</el-button>
      </div>
      <el-tab-pane v-for = "(item,index) in tabData" :key="index" :label="item.title" :name="item.id.toString()" >
        <dragTreeTable :data="treeData" :height="300" :onDrag="onTreeDataChange">
        </dragTreeTable>
        <div v-if="Object.keys(treeData.lists).length < 1"  class="hide">
          暂无数据
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添添加用户组分类 -->
    <el-dialog title="添加顶级菜单" :visible.sync="addSortType" :close-on-click-modal="false">
      <el-form :model="form" :rules="rulesForm"  ref="addSortForm" label-width="100px">
        <el-form-item label="菜单名称" prop="title">
          <el-input placheolder="请输入菜单名称" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="标识" prop="name">
          <el-input placheolder="请输入标识" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="图标" width="30%">
          <icon-select @selected="selectedIcon" mode="form.icon"></icon-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input placheolder="请输入用户组排序" v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input placheolder="请输入说明" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input placheolder="请输入菜单路径" v-model="form.path"></el-input>
        </el-form-item>
        <el-form-item label="菜单组件地址" >
          <el-input placheolder="请输入菜单组件地址" v-model="form.component"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" :value="form.status" placeholder="请选择状态">
            <el-option label="启用" value="Normal"></el-option>
            <el-option label="禁用" value="Fail"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addSortTitle = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addSortForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户组类型 -->
    <el-dialog :title="addGroupTitle" :visible.sync="addGroupType" :close-on-click-modal="false">
      <el-form :model="form" :rules="rulesForm"  ref="addGroupform" label-width="100px">
       <el-form-item label="菜单名称" prop="title">
          <el-input placheolder="请输入菜单名称" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="标识" prop="name">
          <el-input placheolder="请输入标识" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="图标" width="30%">
          <icon-select @selected="selectedIcon" mode="form.icon"></icon-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input placheolder="请输入用户组排序" v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input placheolder="请输入说明" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input placheolder="请输入菜单路径" v-model="form.path"></el-input>
        </el-form-item>
        <el-form-item label="菜单组件地址" >
          <el-input placheolder="请输入菜单组件地址" v-model="form.component"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" :value="form.status" placeholder="请选择状态">
            <el-option label="启用" value="Normal"></el-option>
            <el-option label="禁用" value="Fail"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGroupType = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addGroupform')">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog :title="editGroupTitle" :visible.sync="editGroupType" :close-on-click-modal="false">
      <el-form :rules="rulesForm" :model="form" ref="editform" label-width="100px">
        <el-form-item label="菜单名称" prop="title">
          <el-input placheolder="请输入菜单名称" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="标识" prop="name">
          <el-input placheolder="请输入标识" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="图标" width="30%">
          <icon-select @selected="selectedIcon" mode="form.icon"></icon-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input placheolder="请输入用户组排序" v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input placheolder="请输入说明" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input placheolder="请输入菜单路径" v-model="form.path"></el-input>
        </el-form-item>
        <el-form-item label="菜单组件地址" >
          <el-input placheolder="请输入菜单组件地址" v-model="form.component"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" :value="form.status" placeholder="请选择状态">
            <el-option label="启用" value="Normal"></el-option>
            <el-option label="禁用" value="Fail"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGroupType = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('editform')">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import axios from "axios";
import dragTreeTable from "drag-tree-table";
import IconSelect from "@/components/IconSelect";
import { constants } from 'crypto';

export default {
  name: "index",
  components: { dragTreeTable, IconSelect },
  data() {
    return {
      addSortTitle:"",
      addSortType: false,
      addGroupTitle:"",
      addGroupType: false,
      editGroupTitle:"",
      editGroupType: false,
      firstListData: false,
      parent_id: null,
      edit_id: null,
      form:{
        title: "",
        name:"",
        module_id: "",  //模块 ID
        remark: "",
        sort: 0,
        parent_id: "", //
        permission_id: "",
        icon: " ",
        status: "Normal",
        path: "/menu",
        component: "menu/index"
      },
      rulesForm:{
        title: [{ required: true, validator: titleValiData, trigger: 'change' }],
        name: [{ required: true, validator: nameValiData, trigger: 'change' }],
        sort:[{ required: true, validator: sortValiData, trigger: 'change' }],
      },
      currenltTab: null,
      tabData:null,
      treeData: {
        lists: [],
        columns: [
          {
            type: "selection",
            title: "名称",
            field: "title",
            width: 170,
            align: "left",
            formatter: item => {
              return `<span>${item.title}</span>`;
            }
          },
          {
            title: "图标",
            field: "avatar",
            width: 30,
            align: "left",
            formatter: item => {
              return `<i class='${item.avatar}'></i>`;
            }
          },
          {
            title: "ID",
            field: "id",
            width: 50,
            align: "left",
            formatter: item => {
              return `<span>${item.id}</span>`;
            }
          },
          {
            title: "标识",
            field: "name",
            width: 70,
            align: "left",
            formatter: item => {
              return `<span>${item.name}</span>`;
            }
          },
          {
            title: "排序",
            field: "sort",
            width: 30,
            align: "left",
            formatter: item => {
              return `<span>${item.sort}</span>`;
            }
          },
          {
            title: "最后修改时间",
            field: "sort",
            width: 150,
            align: "left",
            formatter: item => {
              return `<span>${item.updated_at}</span>`;
            }
          },
          {
            title: "说明",
            field: "remark",
            width: 200,
            flex: 1,
            align: "left",
            formatter: item => {
              return `<span>${item.remark}</span>`;
            }
          },
          {
            title: "操作",
            type: "action",
            width: 200,
            align: "left",
            fixed:"right",
            actions: [
              {
                text: "添加子菜单",
                onclick: this.addGroup,
                formatter: item => {
                  return '<i class="el-icon-circle-plus size23"></i>';
                }
              },
              {
                text: "编辑",
                onclick: this.onEdit,
                formatter: item => {
                  return '<i class="el-icon-edit size23"></i>';
                }
              },
              {
                text: "删除",
                onclick: this.ondelete,
                formatter: item => {
                  return '<i class="el-icon-delete size23"></i>';
                }
              }
            ]
          }
        ],
        custom_field: {
          ID: "id",
          name: name,
          sort: "sort",
          lists: "children",
          parent_id: "parent_id"
        }
      }
    };
  },
  created: function(){
    console.group("------created创建完毕状态------");
    this.getMenuData(); // 获取数据
  },
  watch:{
    "addSubForm.title": function (old,data){
      console.log(old,data)
    },
     "tabData": function (old,data){
      console.log(old,data)
    }
  },
  methods: {
    async getMenuData(){
      axios
        .get("/api/v1/module/list/",{
          menu: true
        })
        .then(result => {
          let index =result.data.data.data[0].id.toString();
          this.$set(this,'currenltTab',index);
          this.$set(this,'tabData',result.data.data.data);
          if(!this.firstListData){
            let id = result.data.data.data[0].id;
            axios
            .get("api/v1/menu/list/"+id)
            .then(result => {
              if(Object.keys(result.data.data).length >0){
                this.treeData.lists = result.data.data;
                this.firstListData = true;
              }
            })
            .catch(error => {
              console.log(error);
            });
            }else {
              this.getListData(); 
            }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getListData(){
      let id = this.currenltTab;
        axios
          .get("api/v1/menu/list/"+id)
          .then(result => {
            if(Object.keys(result.data.data).length >0){
                this.treeData.lists = result.data.data;
              }
          })
          .catch(error => {
            console.log(error);
          });
    },
    onTreeDataChange(lists) {
      let data = [];
      this.treeData.lists = lists;
      axios.post('api/v1/menu/sort',{
        data:JSON.stringify(lists)
        })
        .then((result)=>{
        })
    },
    addSort(){
      let form = {
        title: "",
        name:"",
        module_id: this.currenltTab,  //模块 ID
        remark: "",
        sort: 0,
        parent_id: 0, 
        permission_id: 1,
        icon: " ",
        status: "Normal",
        path: "/menu",
        component: "menu/index"
      }
      this.form = form;
      this.addSortType = true;
    },
    onEdit(event){
      this.editTitle = `编辑 [ ${event.title} ] 菜单`;
      this.editGroupType = true;
      this.edit_id = event.id;
      this.form.title = event.title;
      this.form.name = event.name;
      this.form.module_id = event.module_id;
      this.form.remark = event.remark;
      this.form.sort = event.sort;
      this.form.parent_id = event.parent_id;
      this.form.permission_id = event.permission_id;
      this.form.icon = event.icon;
      this.form.status = event.status;
      this.form.path = event.path;
      this.form.component = event.component;
    },
    handleClick(tab, event) {
      this.currenltTab = tab.name;
      this.getListData()
    },
    selectedIcon(e) {
      this.form.icon = e;
    },
    addGroup(event){
      this.addGroupType = true;
      this.parent_id = event.id;
      let form = {
        title: "",
        name:"",
        module_id: this.currenltTab,  //模块 ID
        remark: "",
        sort: 0,
        parent_id: 0, 
        permission_id: 1,
        icon: " ",
        status: "Normal",
        path: "/menu",
        component: "menu/index"
      }
      this.form = form;
    },
    submitForm(formName) {
      console.log("===============================A");
      console.log(this.form)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(formName == 'addSortForm' || formName == 'addGroupform'){
              axios.post('/api/v1/menu/create',{
                title: this.form.title,
                name: this.form.name,
                module_id: this.currenltTab,
                remark: this.form.remark,
                sort: this.form.sort,
                parent_id: this.parent_id ? this.parent_id : 0 ,
                permission_id: this.form.permission_id,
                status: this.form.status,
                path: this.form.path,
                component: this.form.component,
                avatar: this.form.icon
              }).then(result=>{
                this.notice('success', result.data.message);
                this.getListData();
                this.addGroupType = false;
                this.addSortType = false;
              }).catch(error=>{
                let str = '';
                Object.keys(error.response.data.message).forEach((index)=>{
                  str+=error.response.data.message[index][0]+ '<br >';
                });
                this.notice('error', str);
                })
            }else {
              let id = this.edit_id;
              axios.post('/api/v1/menu/edit/'+id,{
                title: this.form.title,
                name: this.form.name,
                module_id: this.currenltTab,
                remark: this.form.remark,
                sort: this.form.sort,
                parent_id: this.parent_id ? this.parent_id : 0 ,
                permission_id: this.form.permission_id,
                status: this.form.status,
                path: this.form.path,
                component: this.form.component,
                avatar: this.form.icon
              }).then(result=>{
                this.notice('success', result.data.message);
                this.getListData();
                this.editGroupType = false;
              }).catch(error=>{
                let str = '';
                Object.keys(error.response.data.message).forEach((index)=>{
                  str+=error.response.data.message[index][0]+ '<br >';
                });
                this.notice('error', str);
                })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    ondelete(event) {
      this.$confirm("您确定要删除此用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          axios.get('/api/v1/menu/delete/'+event.id)
          .then(result=>{
            this.notice('success', result.data.message);
            this.getListData();
            this.addGroupType = false;
          }).catch(error=>{
            this.notice('error', error.response.data.message);
          });
          
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    refresh(){
      this.getListData();
      this.notice('success','刷新成功')
    },
    notice(index, str){
      switch (index){
        case "error":
          this.$message({
             dangerouslyUseHTMLString: true,
            message: str,
            type: "error"
          });
          break;
        case "success":
          this.$message({
            message: str,
            type: "success"
          });
          break;
        case "warning":
          this.$message({
            message: str,
            type: "warning"
          });
          break;
        default:
          this.$message(str);
          break;
      }
    }
  }
}
export function titleValiData (rule, value, callback) {
  const reg = /^[\u4e00-\u9fa5]+$/
  if (!value){
    return callback(new Error('请填写菜单名称'))
  } else if (!reg.test(value)) {
    return callback(new Error('用户组格式错误'))
  } else{
    callback()
  }
}

export function nameValiData (rule, value, callback) {
  const reg = /^[a-zA-Z0-_-\-]+$/
  if (!value) {
    return callback(new Error('请填写标识'))
  } else if (!reg.test(value)) {
    return callback(new Error('标识格式错误'))
  } else {
    callback()
  }
}

export function sortValiData (rule, value, callback) {
  const reg = /^[0-9]*$/;
  if(value === 0){
    callback()
  }else {
      if (!value) {
      return callback(new Error('请填写排序'))
    } else if (!reg.test(value)) {
      return callback(new Error('排序必须为数字'))
    } else {
      callback()
    }
  }
  
};
</script>

<style lang="less" scope>
.hide {
  text-align:center;
  line-height: 33px;
  color: #909399 !important;
  padding: 12px 10px;
  border-bottom: 1px solid #e6e6e6; 
}
.size23 {
  font-size: 23px;
  margin: 0 10px 0 0;
}
.btn-group {
  background-color: #f3f3f3;
  padding: 10px;
}
.drag-tree-table {
  margin: 0 !important;
  font-size: 14px !important;
  .drag-tree-table-header {
    padding: 0 !important;
    background: none !important;
    height: 48px !important;
    border-bottom: 1px solid #e6e6e6;
    .tree-column {
      line-height: 33px;
      color: #909399 !important;
      font-weight: 700 !important;
      text-align: left;
      padding: 12px 10px;
    }
  }
  .drag-tree-table-body {
    .tree-row {
      padding: 0 !important;
      height: 57px !important;
      .tree-column {
        line-height: 33px;
        color: #909399 !important;
        padding: 12px 10px;
      }
    }
  }
}
</style>
